from django.shortcuts import render, redirect
from django.http import HttpResponse
# The line `from django.http import JsonResponse` is importing the `JsonResponse` class from the
# `django.http` module in Django. This class is used to return JSON-encoded responses from Django
# views. It allows you to return JSON data in response to an HTTP request, which is commonly used in
# web development for APIs and AJAX requests.
from django.http import JsonResponse
import json
from django.views.decorators.csrf import csrf_protect


def index(request):
    return HttpResponse("hello world")


@csrf_protect
def login(request):
    return render(request, "login.html")


def hello(request):
    if request.method == 'GET':
        print("GET")
    if request.method == 'POST':
        print("POST")
    return render(request, "goods/index.html", {"message": request.method + " Method, Hello world"})


def helloTemplate(request):
    return render(request, "index.html", {"message": "hello world"})#渲染


def loginGet(request):
    username = request.GET.get("username", "")
    password = request.GET.get("password", "")
    userInfo = {
        "username": username,
        "password": password
    }
    jsonUserInfo = json.dumps(userInfo)
    print(jsonUserInfo)
    print(json.loads(jsonUserInfo))

    return JsonResponse(userInfo)


class UserInfo:
    def __init__(self, username, password):
        self.username = username
        self.password = password

    @staticmethod
    def verify(username, password):
        return username == 'admin' and password == "123456"

    def to_dict(self):
        return {
            'username': self.username,
            'password': self.password,
        }


def loginPost(request):
    username = request.POST.get("username", "")
    password = request.POST.get("password", "")
    user = UserInfo(username, password)
    if user.verify(username, password):
        return render(request, "goods/index.html", {"message": user.to_dict()})
    else:
        return redirect("/static/error.html")
        # return render(request, "login.html", {"message": "用户名或密码错误"})


def blog(request, id, title):
    # 路由变量是直接获取，通过url,restful风格
    return HttpResponse(f"博客id为{id}，标题为{title}")
